package com.toolbox;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import sun.security.acl.AclEntryImpl;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class SplitFile {

    private String fileName;

    public SplitFile(String fileName) {
        this.fileName = fileName;
    }


    public void execute() throws IOException {

        Path mainDataPath = Paths.get(fileName);

        Path parent = mainDataPath.getParent();

        Path fileName = mainDataPath.getFileName();

        List<String> mainSourceList = Files.lines(mainDataPath).collect(Collectors.toList());

        Map<String, List<DTO>> reportDate = mainSourceList.stream().map(i -> JSON.parseObject(i.substring(0, i.length() - 1),DTO.class))
                .collect(Collectors.groupingBy(i -> i.getReportDate()));
        reportDate.forEach((k,v)->{
            try {
                Path path = Paths.get(mainDataPath.toString().replace(".",k+"."));
                if (Files.exists(path)) {
                    Files.delete(path);
                    log.info("delete file name={}",path.toString());
                }

                List<String> finalDatas = v.stream().map(i -> JSON.toJSONString(i) + ",").collect(Collectors.toList());

                Files.write(path, finalDatas);
                log.info("write file name={}",path.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }


    @Data
    public static class DTO{
        private String fundCode;

        private String reportDate;
    }
}
